﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace ueEngine.Web.WebLogic
{
    public class StaticURLRoute : Route
    {
        public StaticURLRoute(string name, string pattern, object defaults)
            : base(pattern, new RouteValueDictionary(defaults), new MvcRouteHandler())
        { 
        }
        public override RouteData GetRouteData(System.Web.HttpContextBase httpContext)
        {
            RouteData routeData = null;
            Regex regex = CreateRegex(Url);
            string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;
            Match pathMath = regex.Match(requestPath);
            if (pathMath.Success)
            {
                routeData = new RouteData(this, RouteHandler);
                // 添加默认选项
                if (Defaults != null)
                {
                    foreach (KeyValuePair<string, object> item in Defaults)
                    {
                        routeData.Values[item.Key] = item.Value;
                    }
                }
                // 匹配域名路由
                for (int i = 1; i < pathMath.Groups.Count; i++)
                {
                    Group group = pathMath.Groups[i];
                    if (group.Success)
                    {
                        string key = regex.GroupNameFromNumber(i);

                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                routeData.Values[key] = group.Value;
                            }
                        }
                    }
                }
                return routeData;
            }
            return routeData;
        }
        private Regex CreateRegex(string source)
        {
            // 替换
            source = source.Replace("/", @"\/?");
            source = source.Replace(".", @"\.");
            source = source.Replace("-", @"\-");
            source = source.Replace("{controller}", "(?<controller>([a-zA-Z0-9_]*))");
            source = source.Replace("{action}","(?<action>([a-zA-Z0-9_]*?))");
            source = source.Replace("{id}", "(?<id>([a-zA-Z0-9_\\-\\/\\=\\.\\$\\*\\+@]*))");
            //source = source.Replace("{", @"(?<");
            //source = source.Replace("}", @">([a-zA-Z0-9_]*))");

            return new Regex("^" + source + "$", RegexOptions.IgnoreCase);
        }
    }
}
